import json

from django.http import JsonResponse, HttpResponse
import logging
from django.views.generic import View

# Create your views here.


# 运行广告活动
from designad.models import DesignAdList, AdVariation, UserAdFileLibrary
from utils.Constants import Constants
from utils.HttpUtils import HttpUtils
from xadmin.models import Log


class AdPlayOrPause(View):
    def get(self, request):
        campaign_id = request.GET.get('id')
        action = request.GET.get('action')
        msg = False
        if action == 'play':
            ad = DesignAdList.objects.filter(campaign_id=campaign_id)
            data = HttpUtils.putHttp(Constants.CAMPAIGNS_PALY_URL, {"campaign_ids": [campaign_id]}, ad[0].adUser_id)
            log = Log(
                user_id=ad[0].adUser_id,
                ip_addr=self.request.META['REMOTE_ADDR'],
                action_flag='play',
                message='运行广告{0}'.format(ad[0].adName)
            )
            log.save()
            if not data is None:
                print(data.text)
                logging.info(data.text)
                if data.status_code == 200:
                    ad.update(status=1)
                    msg = True


        elif action == 'pause':
            ad = DesignAdList.objects.filter(campaign_id=campaign_id)
            data = HttpUtils.putHttp(Constants.CAMPAIGNS_PAUSE_URL, {"campaign_ids": [campaign_id]},
                                     ad[0].adUser_id)
            logging.info(data)
            print(data)
            log = Log(
                user_id=ad[0].adUser_id,
                ip_addr=self.request.META['REMOTE_ADDR'],
                action_flag='pause',
                message='暂停广告{0}'.format(ad[0].adName)
            )
            log.save()
            if not data is None:
                logging.info(data.text)
                print(data.text)
                if data.status_code == 200:
                    ad.update(status=0)
                    msg = True
        return JsonResponse({'success': msg})


class AdVariationPlayOrPause(View):
    def get(self, request):
        campaign_id = request.GET.get('id')
        variation_id = request.GET.get('varId')
        action = request.GET.get('action')
        msg = False
        if action == 'play':
            ad_var = AdVariation.objects.filter(varId=variation_id)
            data = HttpUtils.putVarPlayOrPuaseHttp(Constants.CAMPAIGNS_VARIATION_PALY_URL.format(campaign_id, variation_id),
                                                   ad_var[0].user_id)
            log = Log(
                user_id=ad_var[0].user_id,
                ip_addr=self.request.META['REMOTE_ADDR'],
                action_flag='play',
                message='运行广告内容{0}'.format(ad_var[0].varId)
            )
            log.save()
            if not data is None:
                print(data.text)
                logging.info(data.text)
                if data.status_code == 200:
                    ad_var.update(status=1)
                    msg = True

        elif action == 'pause':
            ad_var = AdVariation.objects.filter(varId=variation_id)
            data = HttpUtils.putVarPlayOrPuaseHttp(Constants.CAMPAIGNS_VARIATION_PAUSE_URL.format(campaign_id, variation_id),
                                                   ad_var[0].user_id)
            log = Log(
                user_id=ad_var[0].user_id,
                ip_addr=self.request.META['REMOTE_ADDR'],
                action_flag='pause',
                message='暂停广告内容{0}'.format(ad_var[0].varId)
            )
            log.save()
            if not data is None:
                logging.info(data.text)
                print(data.text)
                if data.status_code == 200:
                    ad_var.update(status=0)
                    msg = True
        return JsonResponse({'success': msg})


class getUserVariation(View):
    def get(self, request):
        if request.GET.get('style') is not None:
            print(request.GET.get('style'))
            if str(request.GET.get('style')).find('-') >= 0:
                ad_style = (str(request.GET.get('style')).split('-')[1]).split('x')
                width = ad_style[0].strip()
                height = ad_style[1].strip()
                return HttpResponse(json.dumps(list(
                    UserAdFileLibrary.objects.filter(user_id=request.user.id,
                                                     width=width,
                                                     height=height).values('file_id',
                                                                           'adMaterial',
                                                                           'width',
                                                                           'height'))))
            elif str(request.GET.get('style')).find('Web Instant Message') >= 0:
                return HttpResponse(json.dumps(list(
                    UserAdFileLibrary.objects.filter(user_id=request.user.id,
                                                     width=250,
                                                     height=150).values('file_id',
                                                                           'adMaterial',
                                                                           'width',
                                                                           'height'))))
                pass
            return HttpResponse({})
        # return HttpResponse(json.dumps(list(
        #         UserAdFileLibrary.objects.filter(user_id=request.user.id).values('file_id',
        #                                                                          'adMaterial',
        #                                                                          'width',
        #                                                                          'height'))))


